package com.block.channel.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.block.channel.service.ICountInfoService;
import com.block.db.entity.CountInfo;
import com.block.db.entity.CountUvInfo;
import com.block.db.mapper.CountInfoMapper;
import com.block.db.mapper.CountUvInfoMapper;
import com.block.channel.service.ICountUvInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2022-10-27
 */
@Service
public class CountUvInfoServiceImpl extends ServiceImpl<CountUvInfoMapper, CountUvInfo> implements ICountUvInfoService {

    @Resource
    CountInfoMapper countInfoMapper;

    @Async
    @Override
    public void saveUvCountInfo( String channelCode, String reqIp, String userAgent, String randomUuid){


        UserAgent userAgentEntity = UserAgentUtil.parse(userAgent);

        String dateInfo = LocalDate.now().toString();
        CountInfo countInfo = countInfoMapper.getEntryByCodeAndDateLock(dateInfo, channelCode);
        if (ObjectUtil.isNotEmpty(countInfo)){
            CountUvInfo countUvInfo = new CountUvInfo();
            countUvInfo.setCountId(countInfo.getId());
            countUvInfo.setDateInfo(dateInfo);
            countUvInfo.setChannelCode(channelCode);
            countUvInfo.setChannelName(countInfo.getChannelName());
            countUvInfo.setReqIp(reqIp);
            countUvInfo.setUserAgent(userAgent);
            countUvInfo.setRandomUuid(randomUuid);
            countUvInfo.setBrowserName(userAgentEntity.getBrowser().getName());
            countUvInfo.setMobileFlag(userAgentEntity.isMobile()?"1":"0");
            countUvInfo.setPlatformName(userAgentEntity.getPlatform().getName());

            this.save(countUvInfo);
        }
    }

    @Async
    @Override
    public void updateUvCountInfo(String uuidStr, String clientInfo, String recordFlag) {

        CountUvInfo countUvInfo = this.baseMapper.getEntityByRandomUuid(uuidStr);
        if (ObjectUtil.isEmpty(countUvInfo)){
            return;
        }

        CountUvInfo updateEntity = new CountUvInfo();
        updateEntity.setId(countUvInfo.getId());
        updateEntity.setClientInfo(clientInfo);
        updateEntity.setRecordFlag(Integer.valueOf(recordFlag));

        boolean update = this.updateById(updateEntity);

    }

}
